package com.xebest.web.controller.pro;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.github.pagehelper.PageHelper;
import com.xebest.common.base.controller.BASEMessage;
import com.xebest.common.base.controller.BaseController;
import com.xebest.common.base.controller.BaseResponse;
import com.xebest.common.enums.erp.storehouse.VenStoreReceiptTypeEnum;
import com.xebest.common.util.XeBaseUtil;
import com.xebest.config.ParamConfig;
import com.xebest.constant.XeConstans;
import com.xebest.util.SysSetBeanUtils;
import com.xebest.web.form.XeVenProSkuForm;
import com.xebest.web.form.XeVenStoreReceiptDetailForm;
import com.xebest.web.form.XeVenStoreReceiptForm;
import com.xebest.web.model.XeVenStoreInfoEntity;
import com.xebest.web.model.XeVenStoreInventoryEntity;
import com.xebest.web.model.XeVenStoreReceiptEntity;
import com.xebest.web.model.base.XePageInfo;
import com.xebest.web.service.XeVenProSkuService;
import com.xebest.web.service.XeVenStoreInfoService;
import com.xebest.web.service.XeVenStoreInventoryService;
import com.xebest.web.service.XeVenStoreReceiptService;
import com.xebest.web.view.ErpUserInfo;
import com.xebest.web.view.XeVenProSkuView;
import com.xebest.web.view.XeVenProView;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.util.StringUtils;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("xeVenProSku")
@Scope("prototype")
public class XeVenProSkuController extends BaseController {

    //日志记录类
    private static final Logger log = LoggerFactory.getLogger(XeVenProSkuController.class);

    @Autowired
    private XeVenProSkuService xeVenProSkuService;   //库存初始化业务操作
    @Autowired
    private XeVenStoreReceiptService xeVenStoreReceiptService;
    @Autowired
    private XeVenStoreInventoryService xeVenStoreInventoryService;//库存一览操作
    @Autowired
    private  XeBaseUtil xeBaseUtil;
    @Autowired
    private ParamConfig paramConfig;//获取公共配置信息
    @Autowired
    private XeVenStoreInfoService xeVenStoreInfoService;

    /**
     *商品列表
     *@auther wangyp
     */
    @RequestMapping("queryXeVenProSkuList")
    public @ResponseBody BaseResponse queryXeVenProSkuList(@RequestBody XeVenProSkuForm form) {
        log.info("商品列表入参"+ JSONArray.toJSONString(form));
        //验证参数
        if (null == form ) {
            return sendAjaxError(BASEMessage.PARAM_ERROR);
        }
        //拼装参数
        XePageInfo<XeVenProSkuView> xePageInfo;
        PageHelper.startPage(form.getPageNum(), form.getPageSize(), true);
        ErpUserInfo userInfo = SysSetBeanUtils.getErpUserInfo(super.getErpLoginUserInfo());
        form.setUserCode(userInfo.getUserCode());
        try {
        //输出结果
        List<XeVenProSkuView> proSkuList = this.xeVenProSkuService.queryXeVenProSkuList(form);
        //转换商品分类名称
        for (XeVenProSkuView venProSkuView :proSkuList) {
           venProSkuView.setOrgCodeName(xeBaseUtil.getAllCateName(venProSkuView.getCateId()));
        }
            xePageInfo = new XePageInfo<XeVenProSkuView>(proSkuList);
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("proSkuList", proSkuList);
            map.put("xePageInfo", xePageInfo);
            //图片服务器地址
            String picServer = paramConfig.getImgUrl() + XeConstans.ERP_PRO_PIC_DIR ;
            map.put("picServer", picServer);
            return sendAjaxOK(map);
        } catch (Exception e) {
            log.error("商品列表List异常：{}", e);
            return sendAjaxError();
        }
    }

    /**
     *商品列表(采购用)
     * @auther wangyp
     */
    @RequestMapping("queryXeVenProList")
    public @ResponseBody BaseResponse queryXeVenProList(@RequestBody XeVenProSkuForm form) {
        log.info("商品列表入参"+ JSONArray.toJSONString(form));
        // /验证参数
        if (null == form ) {
            return sendAjaxError(BASEMessage.PARAM_ERROR);
        }
        //拼装参数
        XePageInfo<XeVenProView> xePageInfo;
        PageHelper.startPage(form.getPageNum(), form.getPageSize(), true);
        ErpUserInfo userInfo = SysSetBeanUtils.getErpUserInfo(super.getErpLoginUserInfo());
        form.setUserCode(userInfo.getUserCode());
        try {

            //输出结果
            List<XeVenProView> proSkuList = this.xeVenProSkuService.queryXeVenProList(form);
            //转换商品分类名称
            for (XeVenProView venProSkuView :proSkuList) {
                venProSkuView.setCategoryName(xeBaseUtil.getAllCateName(venProSkuView.getCateId()));
            }
            xePageInfo = new XePageInfo<XeVenProView>(proSkuList);
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("proSkuList", proSkuList);
            map.put("xePageInfo", xePageInfo);
            //图片服务器地址
            String picServer = paramConfig.getImgUrl();
            map.put("picServer", picServer);
            map.put("picDir",XeConstans.ERP_PRO_PIC_DIR );
            return sendAjaxOK(map);
        } catch (Exception e) {
            log.error("商品列表List异常：{}", e);
            return sendAjaxError();
        }
    }

    /**
     * 添加商品入库单商品明/*
     * @author 杜春静
     */
    @RequestMapping("saveProStoreReceipt")
    public BaseResponse saveProStoreReceipt(@RequestBody @Validated XeVenStoreReceiptForm entity,
                                            BindingResult bindingResult
                                            ){
        log.info("库存初始化入参"+ JSONArray.toJSONString(entity));
        //验证参数
        if (bindingResult.hasErrors()) {
            FieldError fieldError = bindingResult.getFieldError();
            log.info("添加入库单缺少参数：{}, {}",
                    fieldError.getField(),
                    fieldError.getDefaultMessage());
            return sendAjaxError(BASEMessage.PARAM_ERROR, fieldError.getDefaultMessage());
        }
        //验证参数
        for (XeVenStoreReceiptDetailForm detailForm : entity.getReceiptDetailList()){
            if(StringUtils.isEmpty(detailForm.getCurrentInNum()) || StringUtils.isEmpty(detailForm.getProSku())
                    || StringUtils.isEmpty(detailForm.getBatchPrice()) || StringUtils.isEmpty(detailForm.getProCategoryId())
                    ||StringUtils.isEmpty(detailForm.getCurrentInNum())){
                return sendAjaxError(BASEMessage.PARAM_ERROR);
            }
        }
        XeVenStoreReceiptEntity form =new XeVenStoreReceiptEntity();
        //获取供应商code
        ErpUserInfo userInfo = SysSetBeanUtils.getErpUserInfo(super.getErpLoginUserInfo());
        XeVenStoreInfoEntity xeVenStoreInfoEntity = xeVenStoreInfoService.getStoreTypeByStoreId(entity.getStoreId(),userInfo.getUserCode());
        int result = 0;
        try{
        //转换3零采仓库，4分拨仓库  初始化仓库
        if (xeVenStoreInfoEntity.getStoreType().equals(3) || xeVenStoreInfoEntity.getStoreType().equals(4)){
            XeVenStoreInventoryEntity storeInventory = new XeVenStoreInventoryEntity();
            //添加创建人和修改人
            for (XeVenStoreReceiptDetailForm detailForm:entity.getReceiptDetailList()){
                storeInventory.setUserCode(userInfo.getUserCode());
                storeInventory.setCreateUser(userInfo.getLoginName());
                storeInventory.setModifyUser(userInfo.getLoginName());
                storeInventory.setStoreId(entity.getStoreId());
                storeInventory.setProNum(detailForm.getProNum());
                storeInventory.setProName(detailForm.getProName());
                storeInventory.setProSku(detailForm.getProSku());
                storeInventory.setProMainImg(detailForm.getProMainImg());
                storeInventory.setProCategoryName(detailForm.getProCategoryName());
                storeInventory.setProCategoryId(detailForm.getProCategoryId());
                storeInventory.setProPricingType(detailForm.getProPricingType());
                storeInventory.setProUnit(detailForm.getProUnit());
                storeInventory.setProSpecName(detailForm.getProSpecName());
                storeInventory.setProSepcValue(detailForm.getProSepcValue());
                storeInventory.setFrozenFlag(detailForm.getFrozenFlag());
                result =xeVenStoreInventoryService.initStoreInv(storeInventory);
                if(result == 0){
                    return this.sendAjaxError();
                }
            }

        }else {
            //转换自有 三方  入库单
            String jsonString  = JSON.toJSONString(entity, SerializerFeature.WriteMapNullValue,
                SerializerFeature.WriteNullStringAsEmpty);
            form = JSON.parseObject(jsonString,XeVenStoreReceiptEntity.class);
            form.setUserCode(userInfo.getUserCode());
            //添加创建人和修改人
            form.setCreateUser(userInfo.getLoginName());
            form.setModifyUser(userInfo.getLoginName());
            form.setReceiptType(VenStoreReceiptTypeEnum.INITI_RECEIPT.getValue());
            result = xeVenStoreReceiptService.saveStoreReceipt(form);
            if(result == 0){
                return this.sendAjaxError();
            }
        }
        }catch(Exception e){
            log.error("库存初始化失败，异常信息为：{}"+e);
            return this.sendAjaxError();
        }
        return this.sendAjaxOK();

    }

}
